/*
 * Copyright (c) 2018. cangoonline.net All Rights Reserved.
 * 类名称：MailController.java
 * 创建人：韩伟
 * 联系方式：hanwei@cangoonline.com
 */
package com.cango.mail.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cango.framework.base.opt.DictUtils;
import com.cango.mail.CangoMail;
import com.cango.mail.MailSaver;
import com.cango.mail.MailSender;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: hanwei
 * CreateDate: 2019/9/11
 */
@RestController
@RequestMapping("/")
public class MailController {
    Logger logger = LoggerFactory.getLogger(MailController.class);
    public static final String RESPONSE_CODE_SUCCESS = "0000";
    public static final String RESPONSE_CODE_ERROR = "9999";
    public static final String ERROR_DECRYPT = "9997";
    public static final String ERROR_AUTHCODE_INVALID = "9998";

    @Autowired
    private MailSaver mailSaver;

    @Autowired
    private MailSender mailSerder;

    @Autowired
    private DictUtils dictUtils;


    @RequestMapping(value = "/add" ,method = RequestMethod.POST)
    public HashMap<String,Object> addMail(@RequestParam(required = true) String clientCode, String params){
        String factParam = null;
        HashMap<String,Object> map = new HashMap<String,Object>();
        //验证cliencode
        String key = getKey(clientCode);
        String authCode= getAuthCode(clientCode);

        logger.info("key = ="+key +"==============authcode=="+authCode);
        try {
            factParam = decrypt(params, key);
        } catch (Exception e) {
            logger.error("解密请求参数错误", e);
            map.put("code",ERROR_DECRYPT);
            map.put("msg","解密请求参数错误");
            return map;
        }

        try {
            JSONObject jsonObject = JSONObject.parseObject(factParam);
            JSONObject mailJson = jsonObject.getJSONObject("data");
            if (null == mailJson || !mailJson.containsKey("authCode") || !authCode.equals(mailJson.getString("authCode"))) {
                map.put("code",ERROR_AUTHCODE_INVALID);
                map.put("msg","系统验证码错误");
                return map;
            }


            if (null == mailJson || !mailJson.containsKey("templateCode") || "".equals(mailJson.getString("templateCode"))) {
                map.put("code", RESPONSE_CODE_ERROR);
                map.put("msg","模版代码为空");
                return map;
            }
            if (!mailSaver.checkTemplate(mailJson.getString("templateCode"))) {
                map.put("code", RESPONSE_CODE_ERROR);
                map.put("msg","错误的模版代码");
                return map;
            }
            CangoMail mail = new CangoMail();

            mail.setClientCode(clientCode);
            mail.setCc(mailJson.getString("cc"));
            mail.setBcc(mailJson.getString("bcc"));
            mail.setMailto(mailJson.getString("to"));
            mail.setFrom(mailJson.getString("from"));
            Map<String,Object> sp = json2HashMap(mailJson.getJSONObject("sp"));
            Map<String,Object> cp = json2HashMap(mailJson.getJSONObject("cp"));
            String[] ss = mailSaver.applyTemplate(mailJson.getString("templateCode"),sp,cp);
            mail.setSubject(ss[0]);
            mail.setContent(ss[1]);

            mailSaver.addMail(mail);
            map.put("code",RESPONSE_CODE_SUCCESS);
            map.put("msg","success");
            return map;

        } catch (Exception e) {
            logger.error("新增邮件发生未知错误", e);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            map.put("code",RESPONSE_CODE_ERROR);
            map.put("msg","新增邮件发生未知错误:" + sw.toString());
            return map;
        }
    }

    @RequestMapping(value = "/schedule", method = RequestMethod.POST)
    public HashMap<String,Object> schedule(String method, String params) {
        String factParam = null;
        HashMap<String,Object> map = new HashMap<String,Object>();
        try {
            factParam = decrypt(params, getSelfKey());
        } catch (Exception e) {
            logger.error("解密请求参数错误", e);
            map.put("code",ERROR_DECRYPT);
            map.put("msg","解密请求参数错误");
            return map;
        }

        try {
            JSONObject jsonObject = JSONObject.parseObject(factParam);
            if (null == jsonObject || !jsonObject.containsKey("authCode") || !getSelfAuthCode().equals(jsonObject.getString("authCode"))) {
                map.put("code",ERROR_AUTHCODE_INVALID);
                map.put("msg","系统验证码错误");
                return map;
            }

            mailSerder.sendMail();
            map.put("code",RESPONSE_CODE_SUCCESS);
            map.put("msg","success");
            return map;
        } catch (Exception e) {
            logger.error("调用job程序出现未知错误", e);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            map.put("code",RESPONSE_CODE_ERROR);
            map.put("msg","调用job程序出现未知错误:" + sw.toString());
            return map;
        }
    }


    public String getKey(String clientCode) {
        return mailSaver.getKey(clientCode);
    }

    public String getAuthCode(String clientCode) {
        return mailSaver.getAuthCode(clientCode);
    }
    public String getSelfKey() {
        return dictUtils.getDictEntity(900030001).getDictName();
    }

    public String getSelfAuthCode() {
        return dictUtils.getDictEntity(900030002).getDictName();
    }


    /**
     * 加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new IllegalArgumentException("Argument sKey is null.");
        }
        if (sKey.length() != 16) {
            throw new IllegalArgumentException(
                    "Argument sKey'length is not 16.");
        }
        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
        String tempStr = parseByte2HexStr(encrypted);

        com.thoughtworks.xstream.core.util.Base64Encoder encoder = new com.thoughtworks.xstream.core.util.Base64Encoder();
        return encoder.encode(tempStr.getBytes("UTF-8"));
    }

    /**
     * 解密--先 进行base64解码，在进行16进制转为2进制然后再解码
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {

        if (sKey == null) {
            throw new IllegalArgumentException("499");
        }
        if (sKey.length() != 16) {
            throw new IllegalArgumentException("498");
        }

        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        com.thoughtworks.xstream.core.util.Base64Encoder encoder = new com.thoughtworks.xstream.core.util.Base64Encoder();
        byte[] encrypted1 = encoder.decode(sSrc);

        String tempStr = new String(encrypted1, "utf-8");
        encrypted1 = parseHexStr2Byte(tempStr);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    private Map<String,Object> json2HashMap(JSONObject json){
        Map<String,Object> map = null;
        Gson gson = new Gson();
        //map = gson.fromJson(json.toJSONString(),Type);
        map = json.getInnerMap();
        return map;
    }

    public static void main(String[] args) throws Exception {
        MailController mc = new MailController();
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("clientCode","55");
        JSONObject mailJson = new JSONObject();
        mailJson.put("authCode","1234567890123456");
        mailJson.put("templateCode","db_job_error");
        mailJson.put("to","3,2");
        mailJson.put("cc","4,5");
        mailJson.put("bcc","7,8");
        JSONObject spJson = new JSONObject();
        spJson.put("jobName","test");
        spJson.put("scheduleId",6);
        spJson.put("clientCode","ccs");
        mailJson.put("sp",spJson);
        JSONObject cpJson = new JSONObject();
        cpJson.put("jobName","test");
        cpJson.put("scheduleId",6);
        cpJson.put("clientCode","ccs");
        cpJson.put("remark","jc每日分案");
        cpJson.put("executeTime","2019-09-12 ");
        JSONArray ja = new JSONArray();
        JSONObject j1 = new JSONObject();
        j1.put("id","1");
        j1.put("name","name1");
        JSONObject j2 = new JSONObject();
        j2.put("id","2");
        j2.put("name","name2");
        ja.add(j1);
        ja.add(j2);
        cpJson.put("list",ja);
        cpJson.put("error","错误信息");
        mailJson.put("cp",cpJson);
        mailJson.put("from","hanwei");
        jsonObject.put("data",mailJson);
        System.out.println(jsonObject.toJSONString());
        String s= encrypt(jsonObject.toJSONString(),"1234567890123456");
        System.out.println(s);
    }
}
